# -*- coding: utf-8 -*-
import json
import time
from io import BytesIO

from PIL import Image
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from demo import Constants

import demo.tensorflow.tf_reco as reco
import base64


def hello(request):
    context = {}
    context['hello'] = 'Hello World!!!!!'
    return render(request, 'hello.html', context)


@csrf_exempt
def index(request):
    return "hello world!!!"


import uuid

import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


@csrf_exempt
def upload(request):
    startTime = time.time()
    logger.info("startTime: %s " % (startTime))
    resp = {"startTime": startTime, "endTime": 0, "runtime": 0, "result": ""}
    try:
        print(request.body)
        jsonR = json.loads(request.body)
        print(json.dumps(jsonR, indent=4))
        # 获取图片
        header = jsonR['base64str'].split(",")[0]
        base64_data = jsonR['base64str'].split(",")[1]
        # 将base64的图片转化为byte，去除html的图片标签
        imgData = base64.b64decode(base64_data)
        print("imgData: %s" % (len(imgData)))
        # 图片名称
        img_dir = Constants.getImagesPath() + uuid.uuid1().__str__() + "_" + jsonR['imageName']
        with open(img_dir, 'wb') as file:
            file.write(imgData)
        logs_train_dir = Constants.getTrainsLogDir()
        dstfile, line = reco.handler(img_dir, logs_train_dir)
        resp['result'] = line
        with open(dstfile, "rb") as f:
            # b64encode是编码，b64decode是解码
            dstImg = str(base64.b64encode(f.read()), 'utf-8')

        # header="data:image/jpeg;base64"
        resp['dstImg'] = header + ',' + dstImg
    except BaseException as e:
        print("Error:", e)
    finally:
        endTime = time.time()
        runTime = endTime - startTime
        logger.info("startTime: %s " % (startTime))
        logger.info("endTime: %s " % (endTime))
        logger.info("runTime: %s " % (runTime))
        resp['endTime'] = endTime
        resp['runTime'] = runTime
        print("运行时间 %s" % (runTime))
    return HttpResponse(json.dumps(resp, indent=4), content_type="application/json")
